import { observable, action, computed } from 'mobx';

let uid = 0

class AppleStore {

  @observable buttonText = '摘苹果';

  @observable isPicking = false;
  // apples 列表
  @observable apples = [{
    id: uid++,
    weight: 233,
    isEaten: false
  },
  {
    id: uid++,
    weight: 235,
    isEaten: true
  },
  {
    id: uid++,
    weight: 256,
    isEaten: false
  }];
  // 采摘苹果
  @action.bound appleAdd () {
    if (this.isPicking) {
      return;
    }
    this.isPicking = true;
    this.buttonText = '正在采摘...';
    setTimeout(() => {
      let weight = Math.floor(200 + Math.random() * 50);
      this.isPicking = false;
      this.buttonText = '摘苹果';
      this.apples.push({
          id: uid++,
          weight: weight,
          isEaten: false
      });
    }, Math.random() * 500);
    // fetch('https://hacker-news.firebaseio.com/v0/jobstories.json')
    //         .then(res => {
    //             /** 备注这里的url只是测试用的，这个是之前hackernews的api, 这里只是确保接口是通的，至于数据还是自己mock */
    //             let weight = Math.floor(200 + Math.random() * 50);
    //             this.isPicking = false;
    //             this.buttonText = '摘苹果';
    //             this.apples.push({
    //                 id: uid++,
    //                 weight: weight,
    //                 isEaten: false
    //             });
    //         });
  }
  // 吃掉苹果
  @action.bound eatApple (id) {
    const apples = this.apples.find(ap => ap.id === id)
    apples.isEaten = true;
  }

  @computed get appleCount () {
    return this.apples.filter(apple => !apple.isEaten).length;
  }
  // 未吃的苹果的重量
  @computed get unEatAppleWeight () {
    return this.apples
                  .filter(apple => !apple.isEaten)
                  .reduce((s, apple) => s+= apple.weight, 0);
  }
  // 已吃的苹果的重量
  @computed get hasEatAppleWeight () {
    return this.hasEatAppleCount.reduce((s, apple) => s+= apple.weight, 0);
  }
  // 未吃的苹果的数量
  @action.bound unEatAppleCount () {
    return this.apples.filter(apple => !apple.isEaten);
  }
  // 已经吃了的苹果的数量
  @computed get hasEatApple () {
    return this.apples.filter(apple => apple.isEaten).length;
  }
  // 已经吃了的苹果的数量
  @computed get hasEatAppleCount () {
    return this.apples.filter(apple => apple.isEaten);
  }
}

const apple = new AppleStore();

export default apple;